<?php
include_once("config.php");

function mPrint($val)
{
  // echo "\r\n<pre>\r\n";
  // print_r($val);
  // echo "\r\n</pre>\r\n";
  echo json_encode($val, JSON_UNESCAPED_UNICODE);
}
function mPrintX($val)
{
  // echo "\r\n<pre>\r\n";
  // var_dump($val);
  // echo "\r\n</pre>\r\n";
  die(json_encode($val, JSON_UNESCAPED_UNICODE));
}
function randomString($len = 32, $number = false)
{
  $len = (int) $len;
  $chars = 'ABCDEFGHIJKLMBOPQRSTUFWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  if ($number) $chars = '0123456789';
  $maxPos = strlen($chars) - 1;
  $pwd = '';
  for ($i = 0; $i < $len; $i++) {
    $pwd .= substr($chars, rand(0, $maxPos), 1);
  }
  return $pwd;
}

function pid2Tree($data, $pid = 0)
{
  $tree = [];
  foreach ($data as $value) {
    if ($value['pid'] == $pid) {
      $temp = pid2Tree($data, $value['id']);
      if (count($temp) > 0) {
        $value['children'] = $temp;
      }
      $tree[] = $value;
    }
  }
  return $tree;
  // var tree = [];
  // var temp;
  // for (var i = 0; i < data.length; i++) {
  //   if (data[i].parent_id == parent_id) {
  //     var obj = data[i];
  //     temp = toTree(data, data[i].id);
  //     if (temp.length > 0) {
  //       obj.children = temp;
  //     }
  //     tree.push(obj);
  //   }
  // }
  // return tree;
}

$prem = '';
$defaultUserTable = false;
// $method 可以为 openssl_get_cipher_methods() 返回的方式
function enAes($data, $AesData = defAesOpt, $option = 0)
{
  $res = openssl_encrypt(json_encode($data), $AesData['method'], $AesData['key'], $option, $AesData['iv']);
  return $res;
}
function deAes($data, $AesData = defAesOpt, $option = 0)
{
  if (is_string($data) || is_numeric($data)) {
    // return $data;
    $res = openssl_decrypt($data, $AesData['method'], $AesData['key'], $option, $AesData['iv']);
    return json_decode($res, true);
  }
}
function getToken($cmd, $table = 'users', $keyList = ['type'], $AesData = defAesOpt)
{
  if (is_array($cmd) && is_array($keyList) && isset($cmd['username']) && isset($cmd['password'])) {
    $ret = GetData(['table' => $table, 'username' => $cmd['username'], 'password' => $cmd['password']], 'id,username,password,' . join($keyList, ','));
    if ($ret) {
      $ret = $ret[0];
      $ret['uniqid'] = uniqid();
      $ret = ['token' => enAes($ret, $AesData)];
      return $ret;
    }
  }
}
function Token2user($cmd, $table = 'users', $AesData = defAesOpt)
{
  if (is_array($cmd) && isset($cmd['token'])) {
    $ret = deAes($cmd['token'], $AesData);
    if (is_array($ret) && $ret['TokenOvertime'] > time()) {
      $ret = GetData(['table' => $table, 'id' => $ret['id']]);
      if (is_array($ret) && count($ret) > 0) return $ret[0];
    }
  }
}
function useToken(&$cmd, $table = 'users', $AesData = defAesOpt)
{
  if (is_array($cmd) && isset($cmd['token'])) {
    $ret = deAes($cmd['token'], $AesData);
    $ret = GetData(['table' => $table, 'id' => $ret['id'], 'username' => $ret['username'], 'password' => $ret['password']]);
    // unset($cmd['token']);
    if ($ret) {
      $ret = $ret[0];
      UpData(['table' => $table, 'useTime' => time(), 'where' => ['id' => $ret['id']]]);
      unset($ret['password']);
      return $ret;
    }
  }
}
function ConnectSql()
{
  global $con, $Username, $Password, $ServerName, $TableName;
  if ($con == null) $con = mysqli_connect($ServerName, $Username, $Password, $TableName);
  mysqli_options($con, MYSQLI_OPT_INT_AND_FLOAT_NATIVE, true);
}
ConnectSql();
function CloseSQL()
{
  global $con;
  mysqli_close($con);
  $con = null;
}
function getRule($val)
{
  if (is_string($val)) {
    $str1 = substr($val, 0, 1);
    if (substr($val, 0, 2) == '!=') {
      return 2;
    } elseif (
      $str1 == '>' ||
      $str1 == '<' ||
      $str1 == '='
    ) {
      return 1;
    } elseif (substr($val, 0, 6) == ' like ') {
      return 6;
    } elseif (substr($val, 0, 4) == ' in(') {
      return strlen($val);
    }elseif (substr($val, 0, 8) == ' REGEXP ') {
      return 8;
    }
  }
  return 0;
}
function formatMysql($val)
{
  if (!$val) $val = 0;
  $val = str_replace("\\", "\\\\", $val);
  $val =  str_replace("'", "\'", $val);
  if (substr($val, 0, 6) == ' like ') $val = " like '" . substr($val, 5) . "'";
  return $val;
}
function isNumber($key, $val = false)
{
  $array = [ // $ret = ' ;
    'id', '价格', 'weight', '浏览量', '权限', '类型', '余额', '上级ID', '推荐ID',
    '归属用户', '商品类型', '服务承诺', '预订须知', '车型', '人数', '金额', '到账',
    '商品ID', '归属商家', '归属客户', '评价打分', 'node', 'state','cid'
  ];
  $ret = in_array($key, $array);
  if (!$ret && $val) {
    $len = strlen($key);
    // $rule = ['+','-','*','/'];
    if (substr($val, 0, $len) === $key) $ret = true;
  }
  return $ret;
}
function strIn($str, $in)
{
  if (is_string($in)) $in = [$in];
  $num = count($in);
  for ($i = 0; $i < $num; $i++) {
    if (!(stripos($str, $in[$i]) === false)) return $in[$i];
  }
  return false;
}

function formatGet($val, $logic = 'and')
{
  $logic = ' ' . $logic . ' ';
  if (!$val) return '';
  $p = array_keys($val);
  $ret = '';
  $ret2 = '';
  $str = false;
  $j = 0;
  $arr = [];
  $num = count($p);
  for ($i = 0; $i < $num; $i++) {
    if ($p[$i] === 'weight' || $p[$i] === 'other') continue;
    if (is_array($val[$p[$i]])) $val[$p[$i]] = ' in(' . join($val[$p[$i]], ',') . ')';
    $ret2 = formatMysql($val[$p[$i]]);
    // $ret2 = $val[$p[$i]]; 
    $j = getRule($ret2);
    if ($p[$i] === 'limit') {
      $str = ' limit ' . $ret2;
      continue;
    }
    $ret = $p[$i];
    if ($j) {
      $ret .= ' ' . $ret2;
    } elseif (isNumber($p[$i]) || $val[$p[$i]] === 'CURRENT_TIMESTAMP' || !is_string($val[$p[$i]])) {
      $ret .= '=' . $ret2;
    } else {
      $ret .= '=\'' . $ret2 . '\'';
    }
    $arr[] = $ret;
  }

  if (isset($val['other']) && $val['other'] && strpos($val['other'], ";") === false) $str = $val['other'] . $str;

  if (isset($val['weight']) && $val['weight']) {
    $str = ' ORDER BY power DESC,changeTime DESC' . $str;
  } elseif (substr($str, 0, 1) == ',') {
    $str = ' ORDER BY ' . substr($str, 1);
  }
  if (count($arr)) {
    $ret = ' where ' . implode($logic, $arr) . $str;
  } else {
    $ret = ' where true ' . $str;
  }
  return $ret;
}
function GetData($cmd, $show = '*', $r0 = false, $logic = 'and')
{ // 失败返回假,成功以二维数组形式返回查询到的结果.
  // if ($cmd['table'] != 'users') die(json_encode($cmd));
  if (!isset($cmd['table'])) return false;
  $tab = strtolower($cmd['table']);
  unset($cmd['table']);
  $val = $cmd;
  global $con;
  if (!$show) $show = '*';
  $sql = 'select ';
  $sql .= $show . ' from ';
  // return formatGet($val, $logic);
  $sql .= $tab . formatGet($val, $logic);
  // if ($tab != 'users') return $sql;
  // if($tab == strtolower('itemType')) return $sql;
  // return $sql;
  $result = mysqli_query($con, $sql);
  if ($result === false) return ['error'=>mysqli_error($con)];
  $ret = mysqli_fetch_all($result, MYSQLI_ASSOC);
  mysqli_free_result($result); // 释放结果内存。
  if ($r0 === true && $ret) $ret = $ret[0];
  return $ret;
}
function noSymbol($key)
{
  $sy = ['=', '+', '-', '*', '/'];
  foreach ($sy as $v) {
    if (strpos($key, $v) > 0) return false;
  }
  return true;
}

function formatAdd($val)
{
  unset($val['id']);
  // unset($val['createTime']);
  // unset($val['changeTime']);
  // unset($val['useTime']);
  $p = array_keys($val);
  $ret = '';
  $ret2 = ' (';
  $num = count($p);
  for ($i = 0; $i < $num; $i++) {
    $ret2 .= $p[$i] . ', ';
    if (isNumber($p[$i]) || $val[$p[$i]] === 'CURRENT_TIMESTAMP') $ret .= formatMysql($val[$p[$i]]) . ', ';
    else $ret .= '\'' . formatMysql($val[$p[$i]]) . '\', ';
  }
  if (strlen($ret2) > 2) $ret2 = substr($ret2, 0, -2);
  $ret2 .= ") values (";
  $ret = $ret2 . substr($ret, 0, -2) . ')';
  return $ret;
}
function AddData($cmd)
{ // 失败返回真,成功返回假
  if (isset($cmd[count($cmd) - 1]) && is_array($cmd[0])) {
    $ret = [];
    foreach ($cmd as $value) {
      $ret[] = AddData($value);
    }
    return $ret;
  }
  $tab = $cmd['table'];
  unset($cmd['table']);
  $val = $cmd;
  // return $cmd;
  if ($tab == null) {
    return false;
  }
  global $con;
  $sql = "insert into " . $tab . formatAdd($val);
  // return $sql;
  // mPrintX($sql);
  $result = mysqli_query($con, $sql);
  if ($result === false) return ['error'=>mysqli_error($con)];
  $result = mysqli_query($con, 'select @@IDENTITY');
  $ret = mysqli_fetch_all($result, MYSQLI_ASSOC);
  mysqli_free_result($result); // 释放结果内存。
  // return $ret[0]['@@IDENTITY'];
  // $ret = runSql('select * from ' . $tab . ' where id=' . $ret[0]['@@IDENTITY']);
  // $ret = $ret[0];
  $cmd['id'] = $ret[0]['@@IDENTITY'];
  return $cmd;
}
function formatUp($val)
{
  unset($val['id']);
  // $val['changeTime'] = 'CURRENT_TIMESTAMP';
  $p = array_keys($val);
  $ret = '';
  $num = count($p);
  for ($i = 0; $i < $num; $i++) { // 如果 $p[$i] === 'id' 则跳过
    if ($p[$i] == 'id') continue;
    $ret .= $p[$i];
    if (noSymbol($p[$i])) {
      $ret .= '=';
    }
    if (
      isNumber($p[$i]) ||
      $val[$p[$i]] === 'CURRENT_TIMESTAMP' ||
      !is_string($val[$p[$i]])
    ) {
      $ret .= formatMysql($val[$p[$i]]) . ', ';
    } else {
      $ret .= '\'' . formatMysql($val[$p[$i]]) . '\', ';
    }
  }
  $ret = substr($ret, 0, -2);
  return $ret;
}
function UpData($cmd)
{ // 失败返回真,成功返回假
  if (isset($cmd[count($cmd) - 1]) && is_array($cmd[0])) {
    $ret = [];
    foreach ($cmd as $value) {
      $ret[] = UpData($value);
    }
    return $ret;
  }
  if (!$cmd['table'] || !$cmd['where']) return false;
  unset($cmd['token']);
  $tab = $cmd['table'];
  unset($cmd['table']);
  $where = $cmd['where'];
  unset($where['table']);
  unset($cmd['where']);
  $val = $cmd;
  if (
    $val == null
    || $tab == null
  ) {
    return false;
  }
  global $con;
  $sql = "UPDATE " . $tab . ' set ' . formatUp($val) . formatGet($where);
  // return $sql;
  $result = mysqli_query($con, $sql);
  if ($result === false) return ['error'=>mysqli_error($con)];
  return $cmd;
}
function unsetarr($arr, $uarr)
{
  $a = count($arr);
  $u = count($uarr);
  foreach ($arr as $i => $ak) {
    foreach ($uarr as $k => $v) {
      if ($i === $v) unset($arr[$i]);
    }
  }
  return $arr;
}

function runSql($sql)
{
  global $con;
  $result = mysqli_query($con, $sql);
  $ret = false;
  if ($result && strtolower(substr($sql, 0, 1)) == 's') {
    $ret = mysqli_fetch_all($result, MYSQLI_ASSOC); // 获取全部数据
    mysqli_free_result($result); // 释放结果内存。
  } else {
    $ret = $result;
  }
  return $ret;
}

/*
set @a=IFNULL((select max(id)from 权限),0);
INSERT INTO `tour_data`.`权限` (`名称`, `node`) VALUES ('浏览记录', 1<<@a);
insert INTO itemtype (createTime,changeTime,cuid,name,cid)VALUES(1,2,3,'维修安装',AUTO_INCREMENT);

*/
